package com.xj.demoExcel.easyexcel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import io.vertx.core.json.JsonArray;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UserListener extends AnalysisEventListener<User> {

    List<User> list = new ArrayList<>();

    @Override
    public void invoke(User user, AnalysisContext analysisContext) {
        System.out.println("解析到1条数据：" + user.toString());
        list.add(user);
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        JsonArray jsonArray = new JsonArray();
        for (User obj : list) {
            JsonArray tmpArr = new JsonArray();
            tmpArr.add(obj.getId());
            tmpArr.add(obj.getName());
            tmpArr.add(obj.getSex());

            jsonArray.add(tmpArr);
        }
        System.out.println(jsonArray.encode());
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        //抛出异常则停止读取。如果这里不抛出异常则 继续读取下一行。
        System.out.println("解析失败，但是继续解析下一行:{}" + exception.getMessage());
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            System.out.println(
                    String.format("第{%s}行，第{%s}列解析异常，数据为:{%s}",
                            excelDataConvertException.getRowIndex(),
                            excelDataConvertException.getColumnIndex(),
                            excelDataConvertException.getCellData()
                    )
            );
        }
    }


    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        for (Map.Entry<Integer, String> entry : headMap.entrySet()) {
            System.out.println("key=" + entry.getKey() + " and value=" + entry.getValue());
        }
    }

    public List<User> getList() {
        return list;
    }

    public void setList(List<User> list) {
        this.list = list;
    }
}
